package com.leo.customer.config

import com.leo.result.ResultEntity
import com.sun.media.sound.InvalidFormatException
import org.springframework.http.converter.HttpMessageNotReadableException
import org.springframework.validation.BindException
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseBody
import javax.servlet.http.HttpServletRequest


/**
 * @author 卢浩
 * @date 2020/10/13 2:36 下午
 */
@ControllerAdvice
class GlobalExceptionHandler {

    @ExceptionHandler(value = [BindException::class])
    fun exceptionHandler(e: BindException): ResultEntity<Any> {
        val bindingResult = e.bindingResult
        if (bindingResult.hasErrors()) {
            return ResultEntity.fail(bindingResult.fieldErrors[0].defaultMessage)
        }
        return ResultEntity.fail(e.message)
    }

    @ResponseBody
    @ExceptionHandler(value = [MethodArgumentNotValidException::class])
    fun exceptionHandler(e: MethodArgumentNotValidException): ResultEntity<Any> {
        val bindingResult = e.bindingResult
        if (bindingResult.hasErrors()) {
            return ResultEntity.fail(bindingResult.fieldErrors[0].defaultMessage)
        }
        return ResultEntity.fail(e.localizedMessage)
    }

    /**
     * 请求参数类型转换异常（满足Cause是InvalidFormatException异常类型的条件），不需要打印堆栈信息
     *
     * [HttpMessageNotReadableException] && [InvalidFormatException]
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(HttpMessageNotReadableException::class)
    fun exceptionHandler(e: HttpMessageNotReadableException, request: HttpServletRequest?): ResultEntity<Any> {
        return if (e.cause is InvalidFormatException) {
            //参数类型转换失败，不需要打印堆栈信息
//            logger.error("全局异常处理【参数类型错误】：{}", e.message)
            ResultEntity.fail(e.message)
        } else {
//            logger.error("全局异常处理【系统异常】", e)
            ResultEntity.fail(e.message)
        }
    }

    @ResponseBody
    @ExceptionHandler(value = [Exception::class])
    fun exceptionHandler(e: Exception): ResultEntity<Any> {
        return ResultEntity.fail(e.message)
    }
}
